package com.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.order.common.entiry.ResultCode;
import com.order.common.entiry.ResultEntity;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {

    @SneakyThrows
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //1. 获取请求的URI
        String requestURI = request.getRequestURI();

        //2. 截取
        int index = requestURI.lastIndexOf("/");

        String method = requestURI.substring(index + 1);

        //3.反射
        //3.1 当前Servlet 对象的类型
        Class<? extends BaseController> aClass = this.getClass();
        //3.2 获得 反射的具体方法
        Method declaredMethod = aClass.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
        //3.3 反射调用方法
        declaredMethod.invoke(this, request, response);
    }

    /**
     * 统一响应
     * @param response
     * @param flag   成功标记位
     */
    @SneakyThrows
    protected void writeResult(HttpServletResponse response,  boolean flag) {
        if (flag)
        {
            ResultEntity result = ResultEntity.SUCCESS();

            response.getWriter().write(JSON.toJSONString(result));

        } else {
            ResultEntity result = ResultEntity.ERROR();
            response.getWriter().write(JSON.toJSONString(result));
        }
    }

    @SneakyThrows
    public void writeResult(HttpServletResponse response, ResultCode resultCode) {

        ResultEntity result = new ResultEntity(resultCode);

        response.getWriter().write(JSON.toJSONString(result));
    }

    @SneakyThrows
    protected void writeResultAndData(HttpServletResponse response,  Object data) {

        if(data!=null)
        {


            ResultEntity result = new ResultEntity(ResultCode.SUCCESS, data);
            System.out.println(result);
            System.out.println(JSON.toJSONString(result, SerializerFeature.WriteMapNullValue));
            response.getWriter().write(JSON.toJSONString(result, SerializerFeature.WriteMapNullValue));


        }else {

            ResultEntity result = new ResultEntity(ResultCode.NODATA);

            response.getWriter().write(JSON.toJSONString(result));

        }
    }


}
